# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from mails.models import Dmail
from mails.mailforms import *
from datetime import datetime

@login_required
def listDmail(request):
    latest_dmail_list = Dmail.objects.filter(user=request.user).order_by('-date','-time')
    return render_to_response('mailList.html', {'latest_dmail_list': latest_dmail_list})

@login_required
def newDmail(request,erro=False,idd = -1):
    dict = {}
    dict['form'] = MailForm(initial={'date':datetime.today(),'time':datetime.today()})
    dict['erro'] = erro
    dmail = Dmail()
    if idd != -1 or 'id' in request.GET:
        if idd == -1:
            idd = request.GET['id']
        try:
            dmail = Dmail.objects.get(id=idd,user=request.user)
            dict['dmail'] = dmail
            dict['form'] = MailForm(instance=dmail)
        except:
            pass
    return render_to_response('mailNew.html', dict,context_instance=RequestContext(request))

@login_required
def createDmail(request):
    post = request.POST
    idd = post["id"]

    if (idd == ""):
        dmail = Dmail()
        dmail.user = request.user
    else:
        try:
            dmail = Dmail.objects.get(id=idd)
        except:
            pass

    if (dmail.user == request.user):
        f = MailForm(post, instance=dmail)  
        if f.is_valid():
            f.save()
        else:
            return newDmail(request,f.errors,idd)
            
    return HttpResponseRedirect('list')

@login_required
def eraseDmail(request):
    if "id" in request.GET:
        idd = request.GET["id"]
        try:
            dmail = Dmail.objects.get(id=idd,user=request.user)
            dmail.delete()
        except:
            pass
    return HttpResponseRedirect('list')
